import {
    getToken
} from "@/src/utils/local";
import {
    tansParams,
    blobValidate
} from "@/src/utils/tools";
import $modal from "@/src/plugins/modal.js";
import config from "@/src/config/index.js";
const baseUrl = config.baseUrl;
const httpRequest = (opts, data) => {
    // 是否需要设置 token

    const isToken = (opts.headers || {}).isToken === false;

    let httpDefaultOpts = {
        url: baseUrl +
            (opts.params ? opts.url + "?" + tansParams(opts.params) : opts.url),
        data: opts.data,
        method: opts.method,
        header: opts.method == "get" ? {
            "X-Requested-With": "XMLHttpRequest",
            Accept: "application/json",
            "Content-Type": "application/json; charset=UTF-8",
        } : {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/json; charset=UTF-8",
        },
        dataType: "json",
    };
    // get请求映射params参数
    // if (opts.method === 'get' && opts.params) {
    //   let url = config.url + '?' + tansParams(config.params);
    //   url = url.slice(0, -1);
    //   config.params = {};
    //   config.url = url;
    // }

    if (getToken() && !isToken) {

        httpDefaultOpts.header["token"] = getToken();
        // httpDefaultOpts.header["Authorization"] = "Bearer " + getToken(); // 让每个请求携带自定义token
    }
    // {
    //     'X-Requested-With': 'XMLHttpRequest',
    //     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    // },
    let promise = new Promise(function(resolve, reject) {
        uni
            .request(httpDefaultOpts)
            .then((res) => {

                // resolve(res.data);
                // 未设置状态码则默认成功状态
                const code = res.data.code || 200;
                // 获取错误信息
                const msg = res.data.msg;
                uni.showLoading({
                    mask: true,
                    title: "加载中，请稍后",
                });
                if (code === 401) {
                    uni.clearStorageSync();
                    $modal.msgWarning("登录状态已过期");
                } else if (code === 500) {
                    $modal.msgWarning(msg);

                    reject(new Error(msg));
                } else if (code === 601) {
                    $modal.msgWarning(msg);

                    reject("error");
                } else if (code == 1) {
                    uni.hideLoading();
                    resolve(res.data);
                } else if (code !== 200) {
                    $modal.msgWarning(msg);

                    reject("error");
                } else {
                    uni.hideLoading();
                    resolve(res.data);
                }
            })
            .catch((response) => {
                reject(response);
            });
    });
    return promise;
};
export default httpRequest;